package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.common.ChatHistory;
import org.chen.common.UserQuery;
import org.chen.dto.ClearClientDto;
import org.chen.exception.CustomException;
import org.chen.mapper.ChatHistoryMapper;
import org.chen.mapper.UserQueryMapper;
import org.chen.result.BaseResponse;
import org.chen.result.CommonResponse;
import org.chen.service.ChatHistoryService;
import org.chen.service_enum.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements ChatHistoryService {
    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    @Autowired
    private UserQueryMapper userQueryMapper;

    @Override
    public BaseResponse<List<ChatHistory>> getChatHistory(ChatHistory chatHistory) {
        if (chatHistory == null){
            throw new CustomException(400,"参数错误");
        }
        List<ChatHistory> userId = chatHistoryMapper.selectList(new QueryWrapper<ChatHistory>().eq("userId", chatHistory.getUserId()));
        if (userId == null){
            return BaseResponse.error(ErrorCode.CHAT_HISTORY_NOT_FOUND.getCode(),ErrorCode.CHAT_HISTORY_NOT_FOUND.getMessage(),ErrorCode.CHAT_HISTORY_NOT_FOUND.getMessage());
        }
        return BaseResponse.success(userId);
    }

    @Override
    public CommonResponse saveChatHistory(ChatHistory chatHistory) {
        if (chatHistory == null){
            throw new CustomException(400,"参数错误");
        }
        int insert = chatHistoryMapper.insert(chatHistory);
        if (insert > 0){
            return CommonResponse.success();
        }
        return CommonResponse.error(ErrorCode.SAVE_FAILED.getCode(),ErrorCode.SAVE_FAILED.getMessage(),ErrorCode.SAVE_FAILED.getMessage());
    }

    @Override
    public CommonResponse deleteBatch(ClearClientDto clearClientDto) {
        if (clearClientDto.getChatHistory() == null || clearClientDto.getType() == null){
            throw new CustomException(400,"参数错误");
        }
        if (clearClientDto.getType() == 1){
            chatHistoryMapper.delete(new QueryWrapper<ChatHistory>().eq("userId", clearClientDto.getChatHistory().getUserId()));
        }else {
            userQueryMapper.delete(new QueryWrapper<UserQuery>().eq("userId", clearClientDto.getChatHistory().getUserId()));
        }

        return CommonResponse.success();
    }
}
